import React from 'react'
import WebFont from 'webfontloader'

function draggable(el, handler) {
  let dragging = false

  const buffer = {
    x: 0,
    y: 0
  }

  el.onmousemove = function ({ movementX, movementY }) {
    if (dragging) {
      buffer.x += movementX
      buffer.y += movementY
      handler({ movementX: buffer.x, movementY: buffer.y })
    }
  }

  el.onmouseup = function () {
    dragging = false
    // buffer.x = 0
    // buffer.y = 0
  }

  el.onmousedown = function ({ clientX, clientY }) {
    dragging = true
  }
}

const Canvas = ({ text, color, width, height, fontSize, fontFamily, padding, bold, italic }) => {
  const canvas = React.useRef(null)
  const ctx = React.useRef(null)

  const [offset, setOffset] = React.useState({ x: 0, y: 0 })

  const [loadingFont, setLoadingFont] = React.useState(false)

  React.useEffect(() => {
    ctx.current = canvas.current.getContext('2d')

    // for retina
    canvas.current.width = width * 2
    canvas.current.height = height * 2
    canvas.current.style.width = `${width}px`
    canvas.current.style.height = `${height}px`

    draggable(canvas.current, ({ movementX, movementY }) => {
      setOffset({ x: movementX, y: movementY })
    })
  }, [])

  React.useEffect(() => {
    WebFont.load({
      google: {
        families: [fontFamily]
      },
      loading() {
        setLoadingFont(true)
      },
      active() {
        drawText()
        setLoadingFont(false)
      },
      inactive() {
        setLoadingFont(false)
      }
    })
  }, [fontFamily])

  React.useEffect(drawText, [text, color, fontFamily, width, height, padding, fontSize, bold, italic, offset])

  function drawText() {
    const measure = ctx.current.measureText(text)

    // const fontSize = height - padding * 2
    const fontProperties = []

    if (italic) { fontProperties.push('italic') }
    if (bold) { fontProperties.push('bold') }

    fontProperties.push(`${fontSize * 2}px`)
    fontProperties.push(fontFamily)
    ctx.current.font = fontProperties.filter(Boolean).join(' ');
    ctx.current.textAlign = 'center'
    ctx.current.textBaseline = 'middle'

    // clear canvas
    ctx.current.clearRect(0, 0, canvas.current.width, canvas.current.height);

    // draw text
    ctx.current.fillStyle = color
    ctx.current.fillText(text, width + offset.x, height + offset.y)
  }

  // TODO: export svg
  function exportSVG() {
    const svg = `
    <svg version="1.1"
      baseProfile="full"
      width="${width}" height="${height}"
      xmlns="http://www.w3.org/2000/svg">
           <text  font-family="${fontFamily}"  x="150" y="125" font-size="60" text-anchor="middle" fill="Source Code Pro">SVG</text>

    </svg>
    `
    saveSvg(svg, text)
  }

  function exportPNG() {
    const png = canvas.current.toDataURL('image/png');
    const link = document.createElement('a');
    link.download = `${text}.png`;
    link.href = png;
    link.click();
  }

  return (
    <div>
      <div className="card" style={{ width, height }}>
        <canvas style={{ visibility: loadingFont ? 'hidden' : 'visible' }} width={width} height={height} ref={canvas}></canvas>
      </div>
      <div style={{ textAlign: 'center' }}>
        <a className="button is-primary" onClick={exportPNG}>PNG 下载</a>
        <a className="button" onClick={exportSVG}>SVG 下载</a>
      </div>
    </div>
  )
}

export default Canvas
